﻿using System;
using 售后客户管理.ModelLibrary;

namespace 售后客户管理.Common
{
    public class SqlConnectionHelper
    {
        public System.Data.SqlClient.SqlConnection sqlConnection { get; private set; } = null;
        public SqlConfig SqlConfig
        {
            get { return _sqlConfig; }
            set
            {
                _sqlConfig = value;
                sqlConnection = new System.Data.SqlClient.SqlConnection(getConnectString(SqlConfig));
            }
        }
        private SqlConfig _sqlConfig = new SqlConfig();
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sqlConfig"></param>
        public SqlConnectionHelper(SqlConfig sqlConfig)
        {
            SqlConfig = sqlConfig;
            sqlConnection = new System.Data.SqlClient.SqlConnection(getConnectString(sqlConfig));
        }
        public SqlConnectionHelper(Configs configs,ConfigCode sqlConfigCode)
        {
            
            SqlConfig=GetSqlConfig(configs, sqlConfigCode);
        }

        //test the SqlConfig is connected or disconnected
        public bool testLinks()
        {
            try
            {
                sqlConnection.Open();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                sqlConnection.Close();
            }
        }
        public string getConnectString(SqlConfig sqlConfig)
        {
            return "pooling=true;server=" + sqlConfig.Address + ";"
            + "uid=" + sqlConfig.LgName + ";"
            + "password=" + sqlConfig.LgPass + ";"
            + "database=" + sqlConfig.DbName + ";"
            + "Max Pool Size=" + AppSet.MaxPool.ToString() + ";"
            + "Min Pool Size=" + AppSet.MinPool.ToString() + ";"
            + "Connect Timeout=" + AppSet.Conn_Timeout.ToString() + ";"
            + "Connection Lifetime=" + AppSet.Conn_Lifetime.ToString() + ";"
            + "Asynchronous Processing=" + AppSet.Asyn_Process.ToString() + ";";

        }
        public SqlConfig GetSqlConfig(Configs configs,ConfigCode sqlConfigCode)
        {
            foreach (SqlConfig item in configs)
            {
                if (item.ConfigCode==sqlConfigCode)
                {
                    
                    return item;
                }
            }
            return new SqlConfig();
        }

    }
}
